const mDate = require('./date.js');
				 
module.exports = app => {
	const resEnd = (res,msg)=>{
		res.send(JSON.stringify( msg ) );
		res.end();
	}
	
	const module = {
		async login(body){
			const {acc,pwd } = body;
			let userInfo = await Pool([{sql:`select * from n_user where acc = ? and pwd = ?`, params:[acc,pwd]}]);
			if(!userInfo || !userInfo[0]) return {code:0, msg: '账号或密码错误'}
			return {data:{...userInfo[0], pwd: null}, code:200  } 
		},
		async reg(body){
			let {name,acc,pwd } = body;
			
			if(!name) return {code:0, msg: '请填写昵称！'}
			if(!acc || (acc+ '').length < 6) return {code:0, msg: '请填写6位以上的账号'}
			if(!pwd || (pwd+'').length < 6 || (pwd+'').length > 20 ) return {code:0, msg: '请填写最少6位最大20位的密码！'}
			
			let res = await Pool([{sql:`select * from n_user where acc = ?`, params:[acc]}]);
			if(res && res.length) return {code:0, msg: '账号已被注册！'}
			
			res = await Pool([{sql:`insert into n_user (name,acc,pwd) values(?,?,?)`, params:[name,acc,pwd]}]);
			 
			return this.login(body)
		},
		
		async update(body){
			let {name, pwd, id } = body;
			if(!name) return {code:0, msg: '请填写昵称！'}
			
			const res = await Pool([{sql:` update  n_user set name = ?, pwd = ? where id = ? `, params:[ name, pwd, id ]}]);
			
			return res && res.affectedRows == 1 ? { code:200  } : {code:0, msg: '修改失败'}
		},
		
		
		
	}
	
	app.post('/user/login', (req,res)=> module.login(req.body).then(data=> resEnd(res,data)) );
	app.post('/user/reg', (req,res)=> module.reg(req.body).then(data=> resEnd(res,data)) );
	app.post('/user/update', (req,res)=> module.update(req.body).then(data=> resEnd(res,data)) );
	
}
		

